//
//  SearchViewController.m
//  GiftItems
//
//  Created by lanou3g on 15/9/22.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "SearchViewController.h"
#import "MainTableViewCell.h"
#import "HotSellerTableViewCell.h"
#import "MainBoutiqueModel.h"
#import "HotSelListModel.h"
#import "HotSellerModel.h"
#import "SearchTableViewCell.h"

#define KItemUrl @"http://api.liwushuo.com/v2/search/item?keyword=参数&sort=&offset=0&limit=20"
#define KPostUrl @"http://api.liwushuo.com/v2/search/post?keyword=参数&sort=&offset=0&limit=20"
#import "searchHearderView.h"

@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property (nonatomic,strong)UITableView *tableViewGift;
@property (nonatomic,strong)UITableView *tableViewStrategy;
@property (nonatomic,strong)UIScrollView *ScrollView;
@property (nonatomic,strong)searchHearderView *headerView;
@property (nonatomic,strong)NSMutableArray *ItemsArray;
@property (nonatomic,strong)NSMutableArray *postArray;
@property (nonatomic,strong)NSString *ItemsUrl;
@property (nonatomic,strong)NSString *postUrl;
@property (nonatomic,strong)NSString *NextUrl;
@property (nonatomic,strong)NSString *ItemsFirstUrl;
@property (nonatomic,strong)NSString *postFirstUrl;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addTableView];
    [self addHeaderView];
   
    self.view.backgroundColor = [UIColor whiteColor];
    

    // Do any additional setup after loading the view.
}

- (void)addHeaderView {
    
    self.headerView = [[searchHearderView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 108)];
    [self.view addSubview:self.headerView];
    
    self.headerView.searchBar.delegate = self;
    // 搜索
    [self.headerView.searchButton addTarget:self action:@selector(searchButton:) forControlEvents:(UIControlEventTouchUpInside)];
    // 返回
    [self.headerView.backButton addTarget:self action:@selector(backClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    self.ScrollView.pagingEnabled = YES;
    self.ScrollView.bounces = NO;
    self.tableViewGift.showsVerticalScrollIndicator = NO;
    self.tableViewStrategy.showsVerticalScrollIndicator = NO;
    self.ScrollView.alwaysBounceHorizontal = YES;
    
    
    self.headerView.strategLine.hidden = YES;
    self.headerView.GiftLine.hidden = YES;

    
}

- (void)giftButton {
    [self.tableViewGift reloadData];
    [self.ScrollView setContentOffset:CGPointMake(0, 0)];
    self.headerView.GiftLine.hidden = NO;
    self.headerView.strategLine.hidden= YES;
    
}
- (void)strategyButton {
    [self.tableViewStrategy reloadData];
    
    [self.ScrollView setContentOffset:CGPointMake(kWidth, 0)];
    self.headerView.strategLine.hidden = NO;
    self.headerView.GiftLine.hidden = YES;
    
}


- (void)backClick:(UIButton *)button {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



//searchbar触发方法
- (void)searchButton:(UIButton *)button {
    
    //调用打印 搜索框的内容
    [self searchBarSearchButtonClicked:self.headerView.searchBar];
    
}





//点击搜索按钮触发的功能
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    //上拉加载 下拉刷新 功能
     [self refreshData];
    // 礼物
    [self.headerView.giftButton addTarget:self action:@selector(giftButton) forControlEvents:(UIControlEventTouchUpInside)];
    // 攻略
    [self.headerView.strategyButton addTarget:self action:@selector(strategyButton) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    self.ItemsArray = nil;
    self.postArray = nil;
    
    NSString *strItems = [KItemUrl stringByReplacingOccurrencesOfString:@"参数"withString:searchBar.text];
    NSURL *urlItems = [NSURL URLWithString:[strItems stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    self.ItemsFirstUrl = [NSString stringWithFormat:@"%@",urlItems];
    [self reloadItems:[NSString stringWithFormat:@"%@",urlItems]];
    NSLog(@"%@",urlItems);
    
    
    NSString *strPost = [KPostUrl stringByReplacingOccurrencesOfString:@"参数" withString:searchBar.text];
    NSURL *urlPost = [NSURL URLWithString:[strPost stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    self.postFirstUrl = [NSString stringWithFormat:@"%@",urlPost];
    [self reloadPost:[NSString stringWithFormat:@"%@",urlPost]];
    NSLog(@"%@",urlPost);
    
    
    [self.headerView.searchBar endEditing:YES];
    [self giftButton];
    
    
}

#pragma  mark ---数据解析---
//下拉刷新 上拉加载
- (void)refreshData {
    //上拉加载
    __block SearchViewController *weakSelf = self;
    [self.tableViewGift addRefreshWithRefreshViewType:(LORefreshViewTypeFooterDefault) refreshingBlock:^{
        NSLog(@"/**/*/*/ %@",weakSelf.NextUrl);
        if ([weakSelf.NextUrl isKindOfClass:[NSNull class]]) {
            NSLog(@"坑死爹了");
            [weakSelf.tableViewGift.defaultFooter endRefreshing];
            return ;
        }
            [weakSelf reloadItems:weakSelf.NextUrl];
        [weakSelf.tableViewGift.defaultFooter endRefreshing];
    }];
    // 下拉刷新
    [self.tableViewGift addRefreshWithRefreshViewType:(LORefreshViewTypeHeaderDefault) refreshingBlock:^{
        [weakSelf.ItemsArray removeAllObjects];
        [weakSelf reloadItems:weakSelf.ItemsFirstUrl];
        [weakSelf.tableViewGift.defaultHeader endRefreshing];
    }];
    // 下拉刷新攻略
    [self.tableViewStrategy addRefreshWithRefreshViewType:(LORefreshViewTypeHeaderDefault) refreshingBlock:^{
        [weakSelf.postArray removeAllObjects];
        [weakSelf reloadPost:weakSelf.postFirstUrl];
        [weakSelf.tableViewStrategy.defaultHeader endRefreshing];
    }];
    
}


//Post解析
- (void)reloadPost:(NSString *)url {
    
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *dicData = dic[@"data"];
        for (NSDictionary *items in dicData[@"posts"]) {
            MainBoutiqueModel *model = [MainBoutiqueModel shareDictionary:items];
            [self.postArray addObject:model];
        }
        [self.tableViewStrategy reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];

    
}
//Items解析
- (void)reloadItems:(NSString *)url {
   
    
    [LORequestManger GET:url success:^(id response) {
        NSLog(@"%@",url);
        NSDictionary *dic = (NSDictionary *)response;
        self.NextUrl = dic[@"data"][@"paging"][@"next_url"];
        for (NSDictionary *dictionary in dic[@"data"][@"items"]) {
            HotSellerModel *model = [HotSellerModel shareJsonWithDictionary:dictionary];
            [self.ItemsArray addObject:model];
        }
        [self.tableViewGift reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];

}
// 懒加载
- (NSMutableArray *)postArray {
    if (!_postArray) {
        _postArray = [[NSMutableArray alloc] init];
    }
    return _postArray;
}
- (NSMutableArray *)ItemsArray {
    if (!_ItemsArray) {
        _ItemsArray = [[NSMutableArray alloc] init];
    }
    return _ItemsArray;
}

//添加tableView
- (void)addTableView {
    
    self.ScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 108, kWidth, kHeight)];
    self.ScrollView.contentSize = CGSizeMake(kWidth * 2, 0);
    self.ScrollView.delegate = self;
    [self.view addSubview:self.ScrollView];
    // 礼物tableView
    self.tableViewGift = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 108) style:(UITableViewStylePlain)];
    self.tableViewGift.tag = 100;
    self.tableViewGift.delegate = self;
    self.tableViewGift.dataSource = self;
    self.tableViewGift.separatorStyle = NO;
    [self.ScrollView addSubview:self.tableViewGift];
    
    
    //攻略tableView
    self.tableViewStrategy = [[UITableView alloc] initWithFrame:CGRectMake(kWidth, 0, kWidth, kHeight - 108) style:(UITableViewStylePlain)];
    self.tableViewStrategy.tag = 101;
    self.tableViewStrategy.delegate = self;
    self.tableViewStrategy.dataSource = self;
    self.tableViewStrategy.separatorStyle = NO;
    [self.ScrollView addSubview:self.tableViewStrategy];

    // 注册两个不同table的Cell
   [self.tableViewGift registerClass:[SearchTableViewCell class] forCellReuseIdentifier:@"giftCell"];
    [self.tableViewStrategy registerClass:[MainTableViewCell class] forCellReuseIdentifier:@"strategyCell"];
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 100) {
        return 140;
    }else {
        return 160;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 100) {
        return self.ItemsArray.count;
    }else {
        return  self.postArray.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 100) {
        SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"giftCell" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[SearchTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"giftCell"];
        }
        HotSellerModel *model = self.ItemsArray[indexPath.row];
        [cell setValueForAttributesWithModel:model];
        cell.title.textColor = [UIColor blackColor];
        cell.priceLabel.textColor = [UIColor blackColor];
        cell.likeNum.textColor = [UIColor blackColor];
        
        return cell;
    }else {
        MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"strategyCell" forIndexPath:indexPath];
        if (cell == nil) {
            cell = [[MainTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"strategyCell"];
        }
        cell.LickCountButton.tag = indexPath.row;
        [cell.LickCountButton addTarget:self action:@selector(clickZan:) forControlEvents:(UIControlEventTouchUpInside)];
        
        MainBoutiqueModel *model = self.postArray[indexPath.row];
        NSArray *modelArray = [[StrategyDataBase shareDataBase] findStrategyModelByTitle:model.title];
        MainBoutiqueModel *modelTitle = modelArray.lastObject;
        
        if (modelTitle) {
            [cell.LickCountButton setImage:[UIImage imageNamed:@"profile_btn_like"] forState:UIControlStateNormal];
        }else {
            [cell.LickCountButton setImage:[UIImage imageNamed:@"profile_btn_unlike"] forState:UIControlStateNormal];
            
        }

        
        [cell shareMainImageModel:model];
        
        return cell;
    }
    return 0;
}

// 点赞
- (void)clickZan:(UIButton *)button {
    
    MainBoutiqueModel *model = self.postArray[button.tag];
    
    CAKeyframeAnimation *k = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    k.values = @[@(0.1),@(1.0),@(1.5)];
    k.keyTimes = @[@(0.0),@(0.5),@(0.8),@(1.0)];
    k.calculationMode = kCAAnimationLinear;
    
    NSArray *modelArray = [[StrategyDataBase shareDataBase] findStrategyModelByTitle:model.title];
    MainBoutiqueModel *modelTitle = modelArray.lastObject;
    
    if (!modelTitle) {
        [button setImage:[UIImage imageNamed:@"profile_btn_like"] forState:UIControlStateNormal];
        button.tintColor = [UIColor redColor];
        [[StrategyDataBase shareDataBase] createStrategyListWithName:@"strategyList"];
        [[StrategyDataBase shareDataBase] insertModel:model];
        [[StrategyDataBase shareDataBase] showAlert];
        NSUInteger linkCount = [model.likes_count integerValue] + 1;
        [button setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)linkCount] forState:(UIControlStateNormal)];
    }else
    {
        [button setImage:[UIImage imageNamed:@"profile_btn_unlike"] forState:UIControlStateNormal];
        button.tintColor = [UIColor whiteColor];
        [[StrategyDataBase shareDataBase] createStrategyListWithName:@"strategyList"];
        [[StrategyDataBase shareDataBase] deleteModelWithStrategy:model.title];
        [[StrategyDataBase shareDataBase] deleteAlert];
        [button setTitle:[NSString stringWithFormat:@"%@",model.likes_count] forState:(UIControlStateNormal)];
        
    }
    [button.layer addAnimation:k forKey:@"SHOW"];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView.tag == 100) {
        
        
        HotSellerModel *model = self.ItemsArray[indexPath.row];
        WebViewController *webVC = [[WebViewController alloc] init];
        
        NSString *newUrl = [KGiftDetailsUrl stringByReplacingOccurrencesOfString:@"参数" withString:[NSString stringWithFormat:@"%@",model.ID]];
        
        [LORequestManger GET:newUrl success:^(id response) {
            NSDictionary *dic = (NSDictionary *)response;
            NSLog(@"看看%@",newUrl);
            
            webVC.webUrl = dic[@"data"][@"purchase_url"];
            webVC.nameShare = dic[@"data"][@"name"];
            webVC.imageShare = dic[@"data"][@"cover_image_url"];
            NSLog(@"%@",webVC.webUrl);
            webVC.type = @"热卖";
            [self presentViewController:webVC animated:YES completion:nil];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
        
        
        
        
        

        
        
        NSLog(@"第一个界面%ld",indexPath.row);
    }else {
        
        WebViewController *webView = [[WebViewController alloc] init];
        
        MainBoutiqueModel *model = [[MainBoutiqueModel alloc] init];
        
        model = self.postArray[indexPath.row];
        
        webView.webUrl = [KStrategyUrl stringByReplacingOccurrencesOfString:@"参数" withString:[NSString stringWithFormat:@"%@",model.ID]];
        webView.type = @"攻略";
        
        [self presentViewController:webView animated:YES completion:nil];

        
        NSLog(@"第二个界面%ld",indexPath.row);
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (self.ScrollView.contentOffset.x == 0) {
        [self giftButton];
    }if (self.ScrollView.contentOffset.x == kWidth) {
         [self strategyButton];
    }
    
    [self.tableViewGift reloadData];
    [self.tableViewStrategy reloadData];
    
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
